package com.lzp.mybatis.dao;

import com.lzp.mybatis.dataobject.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * dao层接口实现类方式进行mybatis开发
 *
 * <p>
 * （1）不管是使用XML还是注解配置，mybatis是支持写DAO实现类的
 * （2）DAO实现类使用较少
 * </p>
 */
public class UserMapperImpl {

    private static final String NAME_SPACE = "com.lzp.mybatis.dao.UserMapper";

    private SqlSessionFactory sqlSessionFactory;

    public UserMapperImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public List<User> listAllUser() {
        // 使用工厂创建SqlSession对象
        try (SqlSession session = sqlSessionFactory.openSession();) {
            // 使用SqlSession对象的方法做查询
            return session.selectList(NAME_SPACE + ".listAllUser");
        }
    }

    public void saveUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert(NAME_SPACE + ".saveUser", user);
        sqlSession.commit();
        sqlSession.close();
    }

    public void updateUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.update(NAME_SPACE + ".updateUser", user);
        sqlSession.commit();
        sqlSession.close();
    }

    public void deleteUser(Integer id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.delete(NAME_SPACE + ".deleteUser", id);
        sqlSession.commit();
        sqlSession.close();
    }

    public User findById(Integer id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = sqlSession.selectOne(NAME_SPACE + ".findById", id);
        sqlSession.close();
        return user;
    }


}
